package com.myh.cc.network

import com.blankj.utilcode.utils.LogUtils
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.experimental.CoroutineCallAdapterFactory
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.myh.cc.base.BaseApplication
import com.myh.cc.util.ConstantUtil
import com.myh.cc.util.NetUtil
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 类描述    ：
 * 创建人    ：  mayahao.
 * 创建时间   ：  2018/1/5.
 * 修改人    ：
 * 修改时间   ：
 * 修改备注   ：
 */
object RetrofitManager {

        // qqmusic https://c.y.qq.com/qzone/fcg-bin/
        // 天气预报 http://jisutqybmf.market.alicloudapi.com/
        const val BASE_URL:String =  "https://c.y.qq.com/"

        var appService: AppService

        init {
                val retrofit = Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(initOKhttpClient())
                        .addCallAdapterFactory(CoroutineCallAdapterFactory())
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build()
                appService = retrofit.create(AppService::class.java)
        }

        /**
         * 初始化
         * Okhttp
         */
        private  fun initOKhttpClient(): OkHttpClient{
                // 创建 大小为 10M 的文件缓存 对象
                val cache = Cache(File(BaseApplication.context.cacheDir,"HttpCache"),
                      (1024 * 1024 * 100).toLong())

                // 初始化 OkHttp
                return  OkHttpClient.Builder()
                                .cache(cache)
                                .connectTimeout(6,TimeUnit.SECONDS)
                                .writeTimeout(6,TimeUnit.SECONDS)
                                .addInterceptor{chain -> //缓存
                                        var  request: Request = chain.request()
                                        if (!NetUtil.isConnected(BaseApplication.context)) {
                                                request = request.newBuilder()
                                                        .cacheControl(CacheControl.FORCE_CACHE)
                                                        .build()
                                                LogUtils.d("no network")
                                        }
                                        val originalResponse = chain.proceed(request)
                                        if (NetUtil.isConnected(BaseApplication.context)) {

                                                val cacheControl = request.cacheControl().toString()
                                                originalResponse.newBuilder()
                                                        .header("Cache-Control", cacheControl)
                                                        .removeHeader("Pragma")
                                                        .build()
                                        } else {
                                                originalResponse.newBuilder()
                                                        .header("Cache-Control", "public, only-if-cached, max-stale=" + ConstantUtil.SCACHE_STALE_SEC)
                                                        .removeHeader("Pragma")
                                                        .build()
                                        }

                                        originalResponse

                                } // 缓存
                                .addNetworkInterceptor {chain ->
                                        var  request: Request = chain.request()
                                        if (!NetUtil.isConnected(BaseApplication.context)) {
                                                request = request.newBuilder()
                                                        .cacheControl(CacheControl.FORCE_CACHE)
                                                        .build()
                                                LogUtils.d("no network")
                                        }
                                        val originalResponse = chain.proceed(request)
                                        if (NetUtil.isConnected(BaseApplication.context)) {

                                                val cacheControl = request.cacheControl().toString()
                                                originalResponse.newBuilder()
                                                        .header("Cache-Control", cacheControl)
                                                        .removeHeader("Pragma")
                                                        .build()
                                        } else {
                                                originalResponse.newBuilder()
                                                        .header("Cache-Control", "public, only-if-cached, max-stale=" + ConstantUtil.SCACHE_STALE_SEC)
                                                        .removeHeader("Pragma")
                                                        .build()
                                        }

                                        originalResponse

                                }//Log 日志
                                .addInterceptor { chain ->
                                        
                                        val request: Request = chain.request()
                                        val  t1: Long = System.nanoTime()
                                        LogUtils.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()))
                                        val response: Response = chain.proceed(request)
                                        val t2 = System.nanoTime()
                                        LogUtils.i(String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                                                response.request().url(), (t2 - t1) / 1e6, response.headers()))
                                        response
                                }
                                .build()
        }



}